import os
from PyQt6.QtCore import QTranslator, Qt, QThread, QMetaObject, Q_ARG, pyqtSlot
from PyQt6.QtGui import QAction
from PyQt6.QtWidgets import QApplication, QMainWindow, QStyleFactory, QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, \
    QLabel, QPushButton, QComboBox, QFormLayout, QDialog, QSpinBox, QFontComboBox, QGridLayout, QListWidget, \
    QFileDialog, QLineEdit, QMessageBox

from rpg import file_conversion


class UISettingsDialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)

        self.setWindowTitle(self.tr("界面设置"))
        parent.translate_func.append([self.setWindowTitle, self, "界面设置"])

        layout = QFormLayout()

        self.language_combo = QComboBox()
        for lang in os.listdir('lang'):
            if lang.endswith('.qm'):
                self.language_combo.addItem(lang[:-3])
        language_label = QLabel(self.tr("界面语言"))
        parent.translate_func.append([language_label.setText, self, "界面语言"])
        layout.addRow(language_label, self.language_combo)

        self.style_combo = QComboBox()
        self.style_combo.addItems(QStyleFactory.keys())
        style_label = QLabel(self.tr("界面风格"))
        parent.translate_func.append([style_label.setText, self, "界面风格"])
        layout.addRow(style_label, self.style_combo)

        self.global_font_combo = QFontComboBox()
        global_font_label = QLabel(self.tr("全局字体"))
        parent.translate_func.append([global_font_label.setText, self, "全局字体"])
        layout.addRow(global_font_label, self.global_font_combo)
        
        self.font_size_spinbox = QSpinBox()
        self.font_size_spinbox.setMinimum(10)
        self.font_size_spinbox.setMaximum(30)
        font_size_label = QLabel(self.tr("全局字号"))
        parent.translate_func.append([font_size_label.setText, self, "全局字号"])
        layout.addRow(font_size_label, self.font_size_spinbox)

        self.original_font_combo = QFontComboBox()
        original_font_label = QLabel(self.tr("原文字体"))
        parent.translate_func.append([original_font_label.setText, self, "原文字体"])
        layout.addRow(original_font_label, self.original_font_combo)

        self.original_font_size_spinbox = QSpinBox()
        self.original_font_size_spinbox.setMinimum(10)
        self.original_font_size_spinbox.setMaximum(30)
        original_font_size_label = QLabel(self.tr("原文字号"))
        parent.translate_func.append([original_font_size_label.setText, self, "原文字号"])
        layout.addRow(original_font_size_label, self.original_font_size_spinbox)

        self.translated_font_combo = QFontComboBox()
        translated_font_label = QLabel(self.tr("译文字体"))
        parent.translate_func.append([translated_font_label.setText, self, "译文字体"])
        layout.addRow(translated_font_label, self.translated_font_combo)

        self.translated_font_size_spinbox = QSpinBox()
        self.translated_font_size_spinbox.setMinimum(10)
        self.translated_font_size_spinbox.setMaximum(30)
        translated_font_size_label = QLabel(self.tr("译文字号"))
        parent.translate_func.append([translated_font_size_label.setText, self, "译文字号"])
        layout.addRow(translated_font_size_label, self.translated_font_size_spinbox)

        self.save_button = QPushButton(self.tr("保存"))
        parent.translate_func.append([self.save_button.setText, self, "保存"])
        self.save_button.clicked.connect(self.save_ui_settings)
        layout.addRow(self.save_button)

        self.setLayout(layout)

    def save_ui_settings(self):
        parent = self.parent()
        settings = parent.settings

        translator = QTranslator()
        selected_language = self.language_combo.currentText()
        settings.setValue('language', f'lang/{selected_language}.qm')
        translator.load(f'lang/{selected_language}.qm')
        QApplication.instance().installTranslator(translator)
        parent.retranslate_ui()

        def set_font(widget, font_size_spinbox, font_combo, label):
            font = widget.font()
            font_size = font_size_spinbox.value()
            settings.setValue(f'{label}_font_size', font_size)
            font_family = font_combo.currentFont()
            settings.setValue(f'{label}_font', font_family.family())
            font.setPointSize(font_size)
            font.setFamily(font_family.family())
            widget.setFont(font)

        set_font(QApplication, self.font_size_spinbox, self.global_font_combo, 'global')
        set_font(parent.original_text_edit, self.original_font_size_spinbox, self.original_font_combo, 'original')
        set_font(parent.translated_text_edit, self.translated_font_size_spinbox, self.translated_font_combo, 'translated')

        style = self.style_combo.currentText()
        settings.setValue('style', style)
        QApplication.setStyle(style)

        self.accept()


class MainWindow(QMainWindow):
    def __init__(self, settings):
        super().__init__()
        self.translate_func = []
        self.max_text_length = 0
        self.beam_size = int(settings.value('beam_size')) if settings.contains('beam_size') else 3
        self.device = settings.value('device') if settings.contains('device') else 'cpu'
        self.settings = settings
        self.translator = None
        self.input_cleaner = None
        self.output_cleaner = None
        self.init_ui()
        self.init_settings()
        self.rpg_trans = file_conversion()

    def init_ui(self):
        self.setWindowTitle(self.tr("翻译姬"))
        self.translate_func.append([self.setWindowTitle, self, "翻译姬"])
        self.setGeometry(100, 100, 800, 600)
        
        self.ui_settings_dialog = UISettingsDialog(self)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        main_layout = QVBoxLayout()
        central_widget.setLayout(main_layout)

        tool_bar = self.addToolBar(self.tr("工具栏"))
        self.translate_func.append([tool_bar.setWindowTitle, self, "工具栏"])

        ui_settings_button = QAction(self.tr("界面设置"))
        self.translate_func.append([ui_settings_button.setText, self, "界面设置"])
        ui_settings_button.triggered.connect(self.show_ui_settings_dialog)
        tool_bar.addAction(ui_settings_button)

        extraction_tobe_translated = QAction(self.tr("提取待翻译文件"), self)
        self.translate_func.append([extraction_tobe_translated.setText, self, "提取待翻译文件"])
        extraction_tobe_translated.triggered.connect(self.show_extraction_dialog)
        tool_bar.addAction(extraction_tobe_translated)

        split_translation = QAction(self.tr("拆分译文"), self)
        self.translate_func.append([split_translation.setText, self, "拆分译文"])
        split_translation.triggered.connect(self.show_split_translation)
        tool_bar.addAction(split_translation)

        replacement_original_text = QAction(self.tr("替换原文"), self)
        self.translate_func.append([replacement_original_text.setText, self, "替换原文"])
        replacement_original_text.triggered.connect(self.show_replacement_dialog)
        tool_bar.addAction(replacement_original_text)



    def init_settings(self):
        def init_font(widget, label):
            font = widget.font()
            if self.settings.contains(f'{label}_font_size'):
                font.setPointSize(int(self.settings.value(f'{label}_font_size')))
            if self.settings.contains(f'{label}_font'):
                font.setFamily(self.settings.value(f'{label}_font'))
            widget.setFont(font)

        init_font(QApplication, 'global')



    def show_ui_settings_dialog(self):
        self.ui_settings_dialog.exec()

    def show_extraction_dialog(self):
        files, _ = QFileDialog.getOpenFileName(self, self.tr("选择需要提取的文件"),
                                                filter=self.tr("Mtool提取的待翻译文件 (*.json)"))
        if files:
            self.rpg_trans.extraction_dialog(files)

    def show_split_translation(self):
        files, _ = QFileDialog.getOpenFileName(self, self.tr("选择需要拆分的文件"),
                                                filter=self.tr("提取出的待翻译文件 (*.json)"))
        if files:
            self.rpg_trans.split(files)

    def show_replacement_dialog(self):

        directory = QFileDialog.getExistingDirectory(self, self.tr("选择译文文件夹"))
        if directory:
            files, _ = QFileDialog.getOpenFileName(self, self.tr("选择需替换的文件"),
                                                   filter=self.tr("Mtool提取的待翻译文件 (*.json)"))
            if files:
                self.rpg_trans.replacement(directory, files)

    def retranslate_ui(self):
        for func, context, text in self.translate_func:
            func(context.tr(text))
